package com.atguigu.yuntai.govern.judger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.yuntai.govern.entity.TableInfo;
import com.atguigu.yuntai.govern.entity.GovernanceDetail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 是否有列备注评分器
 */
@Component("HAS_COLUMN_COMMENT")
@Slf4j
public class TableColumnCommentJudger implements Judger {

    //列备注
    public final String OPTION_CODE = "HAS_COLUMN_COMMENT";
    //规范
    public final String OPTION_TYPE = "SPEC";

    /**
     * 根据是否有列备注进行评分
     *
     * @param tableInfo
     * @param busiDate
     * @return
     */
    @Override
    public GovernanceDetail judge(TableInfo tableInfo, String busiDate) {
        GovernanceDetail governanceDetail = new GovernanceDetail(tableInfo);

        String colJson = tableInfo.getColNameJson();
        JSONArray colJsonArray = JSON.parseArray(colJson);
        List lessCommentList = new ArrayList();
        for (int i = 0; i < colJsonArray.size(); i++) {
            JSONObject jsonObject = colJsonArray.getJSONObject(i);
            String comment = jsonObject.getString("comment");
            String colName = jsonObject.getString("name");
            if (comment == null || comment.length() < 2) {
                lessCommentList.add(colName);
            }
        }
        BigDecimal commentScore = BigDecimal.valueOf(lessCommentList.size()).divide(BigDecimal.valueOf(colJsonArray.size(), 2));

        if (lessCommentList.size() == 0) {
            governanceDetail.setGovernanceContent("符合规范");
            governanceDetail.setGovernanceResult("1");
            governanceDetail.setGovernanceScore(BigDecimal.ONE);
            governanceDetail.setOptionCode(OPTION_CODE);
            governanceDetail.setOptionType(OPTION_TYPE);
        } else {
            governanceDetail.setGovernanceContent("缺少字段备注:" + StringUtils.join(lessCommentList, ","));
            governanceDetail.setGovernanceResult("0");
            governanceDetail.setGovernanceScore(commentScore);
            governanceDetail.setOptionCode(OPTION_CODE);
            governanceDetail.setOptionType(OPTION_TYPE);
        }

        return governanceDetail;
    }
}
